#include "connections.h"

Connections::Connections(QObject *parent) :  QObject(parent)
{
    Log::add("[Connections] manager CREATED");
}

Connections::~Connections()
{
    closeAllConnections();

    Log::add("[Connections] manager DELETED");
}

QTcpSocket* Connections::findDataSocket(int descriptor) const
{
    foreach(User *user,_userList){
        if(user->getConnectionID() == descriptor) return user->getDataSocket();
    }
    return 0;
}

QTcpSocket * Connections::findTickSocket(int descriptor) const
{
    foreach(User *user,_userList){
        if(user->getConnectionID() == descriptor) return user->getTickSocket();
    }
    return 0;
}

int Connections::userId(User *user) const
{
    foreach(User *u,_userList)
    {
        if(u == user) return u->getUserID();
    }
    return 0;
}

int Connections::userId(QString &name) const
{
    foreach(User *user,_userList){
        if(user->curentNick == name) return user->getUserID();
    }
    return 0;
}

int Connections::userId(int descriptor) const
{
    foreach(User *user,_userList){
        if(user->getConnectionID() == descriptor) return user->getUserID();
    }
    return 0;
}

QString Connections::getName(int userId) const
{
    foreach(User *user,_userList){
        if(user->getUserID() == userId) return user->curentNick;
    }
    return QString("");
}

QList<User*>& Connections::getUserList()
{
    return _userList;
}

void Connections::addConnection(QTcpSocket *socket)
{
    Log::add(QString("[Connections] NEW connection [") + socket->peerAddress().toString() + QString("]"));
    User *user = new User(socket);
    user->dataSocketState = WaitForQueryTransmission;
    user->tickSocketState = Undefined;
    _userList.append(user);
}

void Connections::removeConnection(QTcpSocket *socket)
{
    Log::add(QString("[Connections] REMOVE connection [") + socket->peerAddress().toString() + QString("]"));
    foreach (User *user,_userList){
        if(user->getDataSocket() == socket){
             delete user;
             _userList.removeOne(user);
        }
    }
}

User* Connections::findUser(QTcpSocket *dataSocket) const{
    foreach(User *user,_userList){
        if(user->getDataSocket() == dataSocket) return user;
    }
    return NULL;
}

User* Connections::findUser(int id) const{
    foreach(User *user,_userList){
        if(user->getUserID() == id) return user;
    }
    return NULL;
}


void Connections::closeAllConnections()
{
    foreach(User *user,_userList){
        delete user;
        user = NULL;
    }
    _userList.clear();

    Log::add(" [Connections] ALL connections CLOSE");
}
